import {
  Component,
  OnInit,
  ElementRef,
  ViewChild,
  Directive,
  OnDestroy,
  EventEmitter,
  Output,
  Input
} from "@angular/core";

import * as _ from "lodash";

declare var BMap;

@Component({
  selector: "app-select-pos",
  templateUrl: "./select-pos.component.html",
  styleUrls: ["./select-pos.component.scss"]
})
export class SelectPosComponent implements OnInit, OnDestroy {
  map: any;

  ac: any;

  address: string;

  @Output()
  onChange: EventEmitter<any> = new EventEmitter();

  @Input()
  onPlace: any = {
    pos: [],
    zoom: "",
    address: ""
  };

  @ViewChild("lmap")
  mapElement: ElementRef;

  @ViewChild("suggest")
  suggestElement: ElementRef;

  @ViewChild("result")
  resultElement: ElementRef;

  isVisible = false;
  isOkLoading = false;

  showModal(): void {
    this.isVisible = true;
  }

  onOpen = () => {
    this.initMap();
    this.initData();
  };

  //回显数据
  initData() {
    console.log(this);
    // this.suggestElement.nativeElement.value = this.onPlace.address;
    // this.address = this.onPlace.address;
    // this.savePlace();
  }

  onOk(): void {
    this.isOkLoading = true;
    const timer = setTimeout(() => {
      this.isVisible = false;
      this.isOkLoading = false;
      clearTimeout(timer);
    }, 100);
  }

  onCancel(): void {
    this.isVisible = false;
  }

  constructor(private el: ElementRef) {}

  async ngOnInit() {}

  ngOnDestroy() {
    this.off(this.ac, "onhighlight", this.onHightLight);
    this.off(this.ac, "onconfirm", this.onConfirm);
  }

  initMap() {
    this.map = null;
    this.ac = null;
    this.map = new BMap.Map(this.mapElement.nativeElement);
    this.map.centerAndZoom(
      this.onPlace.address || "北京",
      this.onPlace.zoom || 12
    );
    // 初始化地图,设置城市和地图级别。
    this.ac = new BMap.Autocomplete({
      input: this.suggestElement.nativeElement,
      location: this.map
    }); //建立一个自动完成的对象
    const timer = setTimeout(() => {
      if (this.onPlace.address) {
        this.suggestElement.nativeElement.value = this.onPlace.address;
      }
      clearTimeout(timer);
    }, 0);
    this.addListen();
  }

  on(el, type, fn, opts: any = {}) {
    el && el.addEventListener(type, fn, opts);
  }

  off(el, type, fn, opts: any = {}) {
    el && el.removeEventListener(type, fn, opts);
  }

  // loadScript(url) {
  //   const script = document.createElement('script');
  //   script.setAttribute('src', url);
  //   window.document.body.appendChild(script);
  //   return new Promise(resolve => {
  //     script.onload = function() {
  //       resolve();
  //     };
  //   });
  // }

  onHightLight = (e: any) => {
    //鼠标放在下拉列表上的事件
    let str = "";
    let _value = e.fromitem.value;
    let value = "";
    if (e.fromitem.index > -1) {
      value =
        _value.province +
        _value.city +
        _value.district +
        _value.street +
        _value.business;
    }
    str =
      "FromItem<br />index = " + e.fromitem.index + "<br />value = " + value;

    value = "";
    if (e.toitem.index > -1) {
      _value = e.toitem.value;
      value =
        _value.province +
        _value.city +
        _value.district +
        _value.street +
        _value.business;
    }
    str +=
      "<br />ToItem<br />index = " + e.toitem.index + "<br />value = " + value;
    this.resultElement.nativeElement.innerHTML = str;
  };

  onConfirm = (e: any) => {
    //鼠标点击下拉列表后的事件
    let _value = e.item.value;
    this.address =
      _value.province +
      _value.city +
      _value.district +
      _value.street +
      _value.business;
    this.resultElement.nativeElement.innerHTML =
      "onconfirm<br />index = " +
      e.item.index +
      "<br />address = " +
      this.address;

    this.savePlace();
  };

  addListen() {
    this.on(this.ac, "onhighlight", this.onHightLight);
    this.on(this.ac, "onconfirm", this.onConfirm);
  }

  savePlace() {
    this.map.clearOverlays(); //清除地图上所有覆盖物
    const local = new BMap.LocalSearch(this.map, {
      //智能搜索
      onSearchComplete: () => {
        const pp = local.getResults().getPoi(0).point; //获取第一个智能搜索的结果
        this.onPlace = {
          pos: pp,
          zoom: 18,
          address: this.address
        };
        this.onChange.emit(_.merge({}, this.onPlace));
        this.map.centerAndZoom(pp, this.onPlace.zoom);
        this.map.addOverlay(new BMap.Marker(pp)); //添加标注
      }
    });
    local.search(this.address);
  }
}
